package com.code.telegram.services.impl;

import com.code.consts.CommonConsts;
import com.code.models.robot.RobotRewardFlow;
import com.code.telegram.consts.TelegramCommonConsts;
import com.code.telegram.daos.task.RobotRewardFlowMapper;
import com.code.telegram.managers.HttpManager;
import com.code.telegram.services.ChatMemberGroupService;
import com.code.telegram.services.RobotRewardFlowService;
import com.code.utils.SnowFlakeIdUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 机器人奖励服务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class RobotRewardFlowServiceImpl implements RobotRewardFlowService {

    @Resource
    RobotRewardFlowMapper robotRewardFlowMapper;

    @Resource
    ChatMemberGroupService chatMemberGroupService;

    @Resource
    RequestWalletService requestWalletService;

    @Resource
    HttpManager httpManager;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public int insertRobotRewardFlow(RobotRewardFlow robotRewardFlow) {
        String walletAddress = robotRewardFlow.getWalletAddress();
        String amount = robotRewardFlow.getAmount();
        Integer exitsRobotRewardFlow = robotRewardFlowMapper.existRobotRewardFlowByWalletAddressAndAmount(walletAddress, amount);
        int count = 0;
        if (null == exitsRobotRewardFlow) {
            robotRewardFlow.setSerialNo("BZ" + SnowFlakeIdUtil.defaultId());
            robotRewardFlow.setDeleted(0);
            robotRewardFlow.setCreatedAt(new Date());
            robotRewardFlow.setUpdatedAt(new Date());
            try {
                count = robotRewardFlowMapper.insert(robotRewardFlow);
                if (count > 0) {
                    // 发放50Tp
                    requestWalletService.transferAmountToAddr(walletAddress, amount);
                }
            } catch (Exception e) {
                String chatId = robotRewardFlow.getChatId();
                // 删除加群记录
                chatMemberGroupService.deleteChatMemberGroup(chatId, TelegramCommonConsts.BZ_PLAN_GROUP);
                httpManager.sendMessage(Long.parseLong(chatId), TelegramCommonConsts.RE_JOIN_BZ_GROUP_MESSAGE);
                throw e;
            }
        }
        return count;
    }

    @Override
    public Boolean existRobotRewardFlowByWalletAddressAndAmount(String walletAddress, String amount) {
        return null != robotRewardFlowMapper.existRobotRewardFlowByWalletAddressAndAmount(walletAddress, amount);
    }

    @Override
    public Boolean existBzRewardFlowByWalletAddressAndAmount(String walletAddress, String amount) {
        return null != robotRewardFlowMapper.existBzRewardFlowByWalletAddressAndAmount(walletAddress, amount, "BZ");
    }

}
